package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

// 跨域中间件
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

func main() {
	r := gin.Default()
	r.Use(Cors())
	gin.SetMode(viper.GetString("mode"))
	// todo 将接口改成restful接口。
	user := r.Group("/api/user")
	{
		user.GET("/list", UserHandler.UserListHandler)
		user.GET("/info/:id", UserHandler.UserInfoHandler)
		user.POST("/add", UserHandler.AddUserHandler)
		user.POST("/edit", UserHandler.EditUserHandler)
		user.DELETE("/delete/:id", UserHandler.DeleteUserHandler)
	}
	//todo 测试这几个api
	book := r.Group("/api/book")
	{
		book.GET("/info/:userId/:bookName", BookHandler.BookInfoHandler)
		book.GET("/list", BookHandler.BookListHandler)
		book.POST("/add", BookHandler.AddBookHandler)
		book.PATCH("/edit", BookHandler.EditBookHandler)
		book.DELETE("/delete/:userId/:bookName", BookHandler.DeleteBookHandler)
	}
	// todo 测试这几个api
	chapter := r.Group("/api/chapter")
	{
		chapter.GET("list", ChapterHandler.ChapterListHandler)
		chapter.GET("/info/:userId/:bookName/:chapterId", ChapterHandler.ChapterInfoHandler)
		chapter.POST("/add", ChapterHandler.AddChapterHandler)
		chapter.POST("/edit", ChapterHandler.EditChapterHandler)
		chapter.GET("/delete/:userId/:bookName/:chapterId", ChapterHandler.DeleteBookHandler)
	}
	// todo 测试这几个api
	design := r.Group("/api/design")
	{
		design.GET("/info/:dId", DesignHandler.GetCardContenHandler)
		design.GET("/list", DesignHandler.GetAllCardHandler)
		design.GET("/info/type", DesignHandler.GetOneTypeCardHandler)
		design.POST("/add", DesignHandler.AddHandler)
		design.POST("/edit", DesignHandler.Edit)
		design.GET("/delete", DesignHandler.Delete)

	}
	port := viper.GetString("port")
	r.Run(port)

}
